package net.maergaiyun.controller;

import net.maergaiyun.controller.request.ShortLinkAddRequest;
import net.maergaiyun.controller.request.ShortLinkDelRequest;
import net.maergaiyun.controller.request.ShortLinkPageRequest;
import net.maergaiyun.controller.request.ShortLinkUpdateRequest;
import net.maergaiyun.enums.BizCodeEnum;
import net.maergaiyun.service.ShortLinkService;
import net.maergaiyun.util.JsonData;
import net.maergaiyun.vo.ShortLinkVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@RestController
@RequestMapping("/api/link/v1")
public class ShortLinkController {

    @Autowired
    private ShortLinkService shortLinkService;

    @Value("${rpc.token}")
    private String rpcToken;

    @PostMapping("add")
    public JsonData createShortLink(@RequestBody ShortLinkAddRequest shortLinkAddRequest) {
        JsonData jsonData = shortLinkService.createShortLink(shortLinkAddRequest);
        return jsonData;
    }

    @PostMapping("page")
    public JsonData pageByGroupId(@RequestBody ShortLinkPageRequest request) {
        Map<String, Object> result = shortLinkService.pageByGroupId(request);
        return JsonData.buildSuccess(result);
    }

    @PostMapping("del")
    public JsonData del(@RequestBody ShortLinkDelRequest request) {
        JsonData jsonData = shortLinkService.del(request);
        return jsonData;
    }

    @PostMapping("update")
    public JsonData update(@RequestBody ShortLinkUpdateRequest request) {
        JsonData jsonData = shortLinkService.update(request);
        return jsonData;
    }

    @GetMapping("check")
    JsonData check(@RequestParam("shortLinkCode") String shortLinkCode, HttpServletRequest request) {
        String requestToken = request.getHeader("rpc-token");
        if (requestToken.equalsIgnoreCase(rpcToken)) {
            ShortLinkVO shortLinkVO = shortLinkService.parseShortLinkCode(shortLinkCode);
            return shortLinkVO == null ? JsonData.buildResult(BizCodeEnum.SHORT_LINK_NOT_EXIST) : JsonData.buildSuccess();
        } else {
            return JsonData.buildError("非法访问");
        }
    }
}
